package com.emm.yixun.mobile.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.GetMemberScoreList;
import com.emm.yixun.mobile.ui.analysis.AnalysisListViewActivity;
import com.emm.yixun.mobile.ui.analysis.CalculatePriceAnalysisActivity;
import com.emm.yixun.mobile.ui.analysis.CustomerAnalysisActivity;
import com.emm.yixun.mobile.ui.analysis.DealHousingActivity;
import com.emm.yixun.mobile.ui.analysis.HousingTypeAnalySisActivity;
import com.emm.yixun.mobile.ui.analysis.NotSignedBackActivity;
import com.emm.yixun.mobile.ui.analysis.SalesTargetActivity;
import com.emm.yixun.mobile.ui.analysis.TimeAnalysisActivity;
import com.eroad.product.tools.PickerView;
import com.eroad.product.tools.PickerView.onSelectListener;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import xf.tools.Loading;

/**
 * 
 * <p>
 * <b>Title：</b> 分析模块
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 * 
 * @author tangxin
 * @date 2016年12月8日 上午11:10:55
 */
public class AnalysisMainFragment extends Fragment {

	private static final String TAG = "AnalysisMainFragment";

	FragmentActivity root = null;

	/** 标题 */
	TextView title_main;

	/** 统计分析 */
	LinearLayout open_customer_analysis;

	/** 工作量统计 */
	LinearLayout open_listview;

	/** 认筹 */
	TextView count_rencou;

	/** 签约 */
	TextView count_qianyue;

	/** 认购 */
	TextView count_rengou;

	/** 筛选菜单模块 */
	LinearLayout open_layout;

	/** 时间类型。默认今天 */
	String timeType = "1";

	/* ---公用选择框--- */
	View view;
	PopupWindow popu;

	/** 选中内容 */
	String selectName;

	/** 选中下标 */
	int SelectID;

	/** 菜单选项列表 */
	ArrayList<String> listname;
	/* ---公用选择框--- */

	/** 时间展示 */
	TextView name_time;

	/** 签约金额 */
	TextView count_qianyue_price;

	/** 认购金额 */
	TextView count_rengou_price;

	/** 回款金额 */
	TextView count_huikuan_price;

	/** 已签约未回款 */
	LinearLayout not_signed_back;

	/** 销售指标 */
	LinearLayout xiaoshou_view;

	/** 成交房产类型分析 */
	TextView open_housingtype;

	/** 存量时间分析 */
	TextView open_time_housing;

	/** 成交房源分析 */
	TextView deal_housing;

	/** 存量房源分析 */
	TextView deal_housing2;

	/** 算价分析 */
	TextView open_calculatepriceAnalyssis;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.analysis_main_fragment, null);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		root = getActivity();

		initView();
		initBtn();
		getMemberScoreList(timeType);
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		if (hidden) {
			Log.v(TAG, "Fragment的onPause");
		} else {
			Log.v(TAG, "Fragment的onResume");
			if (EmmApplication.IS_RELOAD_ANALYSIS) {// 运营分析是否刷新
				EmmApplication.IS_RELOAD_ANALYSIS = false;
				getMemberScoreList(timeType);// 调用接口刷新数据
			}
		}
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化view
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月8日 上午11:26:32
	 */
	private void initView() {
		title_main = (TextView) root.findViewById(R.id.analysis_include).findViewById(R.id.title_main);
		title_main.setText(getString(R.string.analusis));
		open_customer_analysis = (LinearLayout) root.findViewById(R.id.open_customer_analysis);
		open_listview = (LinearLayout) root.findViewById(R.id.open_listview);
		count_rencou = (TextView) root.findViewById(R.id.count_rencou);
		count_qianyue = (TextView) root.findViewById(R.id.count_qianyue);
		count_rengou = (TextView) root.findViewById(R.id.count_rengou);
		open_layout = (LinearLayout) root.findViewById(R.id.open_layout_analysis);
		name_time = (TextView) root.findViewById(R.id.name_time_analysis);
		count_qianyue_price = (TextView) root.findViewById(R.id.count_qianyue_price);
		count_rengou_price = (TextView) root.findViewById(R.id.count_rengou_price);
		count_huikuan_price = (TextView) root.findViewById(R.id.count_huikuan_price);
		not_signed_back = (LinearLayout) root.findViewById(R.id.not_signed_back);
		xiaoshou_view = (LinearLayout) root.findViewById(R.id.xiaoshou_view);
		open_housingtype = (TextView) root.findViewById(R.id.open_housingtype);
		open_time_housing = (TextView) root.findViewById(R.id.open_time_housing);
		deal_housing = (TextView) root.findViewById(R.id.deal_housing);
		deal_housing2 = (TextView) root.findViewById(R.id.deal_housing2);
		open_calculatepriceAnalyssis = (TextView) root.findViewById(R.id.open_calculatepriceAnalyssis);
		RelativeLayout main_head_top_rela = (RelativeLayout) root.findViewById(R.id.analysis_include).findViewById(
				R.id.main_head_top_rela);
		BaseActivity.SetViewHeight(main_head_top_rela);// 更改relativelayout的高度
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化监听事件
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月13日 下午6:26:06
	 */
	private void initBtn() {

		// 统计分析
		open_customer_analysis.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(root, CustomerAnalysisActivity.class));
			}
		});

		// 工作量统计
		open_listview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(root, AnalysisListViewActivity.class));
			}
		});

		// 筛选菜单模块
		open_layout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				listname = new ArrayList<String>();
				listname.add("今天");
				listname.add("昨天");
				listname.add("本周");
				listname.add("上周");
				listname.add("本月");
				listname.add("上月");
				listname.add("近三月");
				listname.add("今年");
				SetzpPopu(listname, "时间选择", name_time);
			}
		});

		// 已签约未回款
		not_signed_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(root, NotSignedBackActivity.class));
			}
		});

		// 销售指标
		xiaoshou_view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(root, SalesTargetActivity.class));
			}
		});

		// 成交房产类型分析
		open_housingtype.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(root, HousingTypeAnalySisActivity.class));
			}
		});

		// 存量时间分析
		open_time_housing.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(root, TimeAnalysisActivity.class));
			}
		});

		// 成交房源分析
		deal_housing.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(root, DealHousingActivity.class);
				intent.putExtra("TypeHousing", "1");
				startActivity(intent);
			}
		});

		// 存量房源分析
		deal_housing2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(root, DealHousingActivity.class);
				intent.putExtra("TypeHousing", "2");
				startActivity(intent);
			}
		});

		// 算价分析
		open_calculatepriceAnalyssis.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(root, CalculatePriceAnalysisActivity.class));
			}
		});
	}

	/**
	 * <p>
	 * <b>Title：</b> 选项框
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param listname
	 * @param title
	 * @param ed
	 * @author tangxin
	 * @date 2016年12月21日 下午3:31:34
	 */
	public void SetzpPopu(final List<String> listname, String title, final TextView ed) {

		view = LayoutInflater.from(root).inflate(R.layout.popu_zp, null);
		popu = new PopupWindow(view, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
				android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);
		popu.setFocusable(true);
		popu.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
		popu.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		popu.showAtLocation(view, Gravity.BOTTOM, 0, 0);
		popu.showAsDropDown(view, 0, 0);
		popu.setFocusable(true);
		popu.setOutsideTouchable(true);
		view.setFocusable(true);
		view.setFocusableInTouchMode(true);

		view.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					popu.dismiss();
					EmmApplication.setLog(root);
				}
				return false;
			}
		});

		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				popu.dismiss();
				EmmApplication.setLog(root);
			}
		});

		PickerView select_pick = (PickerView) view.findViewById(R.id.select_pick);
		TextView shuerbtn = (TextView) view.findViewById(R.id.shuerbtn);
		RelativeLayout relative_all = (RelativeLayout) view.findViewById(R.id.relative_all);
		ImageView dis_btn = (ImageView) view.findViewById(R.id.dis_btn);
		TextView title_select = (TextView) view.findViewById(R.id.title_select);

		selectName = listname.get(0);

		// 取消
		dis_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				popu.dismiss();
				EmmApplication.setLog(root);
			}
		});

		title_select.setText(title);

		// 设置数据到滑动选择控件
		select_pick.setData(listname);
		select_pick.setOnSelectListener(new onSelectListener() {
			@Override
			public void onSelect(String text, int id) {
				// 选择的
				selectName = text;
				SelectID = id;
			}
		});

		// 默认选择
		select_pick.setSelected(0);
		shuerbtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 确定
				popu.dismiss();
				EmmApplication.setLog(root);
				ed.setText(selectName);

				if ("今天".equals(selectName)) {
					timeType = "1";
				} else if ("昨天".equals(selectName)) {
					timeType = "2";
				} else if ("本周".equals(selectName)) {
					timeType = "3";
				} else if ("上周".equals(selectName)) {
					timeType = "4";
				} else if ("本月".equals(selectName)) {
					timeType = "5";
				} else if ("上月".equals(selectName)) {
					timeType = "6";
				} else if ("近三月".equals(selectName)) {
					timeType = "7";
				} else if ("今年".equals(selectName)) {
					timeType = "8";
				}

				getMemberScoreList(timeType);
			}
		});

		relative_all.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 消耗点击事件
			}
		});
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 刷新数据
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月8日 上午11:36:10
	 */
	public void Reload() {
		getMemberScoreList(timeType);
	}

	/** 个人成绩 */
	GetMemberScoreList getScore;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 个人成绩查询接口
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param timeType
	 * @author tangxin
	 * @date 2016年12月8日 上午11:36:28
	 */
	private void getMemberScoreList(String timeType) {
		Log.v(TAG, "timeType-->" + timeType);
		if (!EmmApplication.isErrorCode()) {
			EmmApplication.T();
			return;
		}
		EmmApplication.updateUrl("getMemberScoreList");
		Map<String, String> map = new HashMap<String, String>();
		map.put("version", EmmApplication.getPackageManager(5));
		map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
		map.put("token", EmmApplication.getToken());
		map.put("userId", EmmApplication.getUserId());
		map.put("timeType", timeType);
		map.put("projectCode", EmmApplication.getProjectCode());
		map.put("terminalCode", EmmApplication.getPackageManager(2));
		map.put("scoreCategory", "2");
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("params", map);
		JSONObject json = new JSONObject(paramsMap);
		String jsonstr = json.toString();
		RequestParams params = new RequestParams();
		params.put("body", jsonstr);
		Log.v(TAG,"getMemberScoreList-->post"+ EmmApplication.urlStr + "?body=" + jsonstr);
		AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
		asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束error:" + error + "==" + content);
			}

			@Override
			public void onFinish() {
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束");
				super.onFinish();
			}

			@Override
			public void onStart() {
				super.onStart();
				Loading.hideDialogForLoading();
				Loading.showDialogForLoading(root, "正在加载...", false, true, 60000);
				Log.v(TAG, "请求开始");
			}

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				if (content == null) {
					return;
				}
				Log.v(TAG, "content===>" + content);
				JSONObject jsonObj = JSONObject.parseObject(content);
				JSONObject resData = (JSONObject) jsonObj.get("resData");
				if (resData == null) {
					Log.v(TAG, "信息返回值为空");
					return;
				}

				getScore = JSONObject.parseObject(resData.toString(), GetMemberScoreList.class);

				if ("1".equals(getScore.getResult())) {
					Log.v("获取成功", "");

					count_rencou.setText(getScore.getRcScoreNum());// 认筹数

					count_rengou.setText(getScore.getRgScoreNum());// 认购数

					count_qianyue.setText(getScore.getQyScoreNum());// 签约数

					count_qianyue_price.setText(getScore.getSignedAmount());// 签约金额

					count_rengou_price.setText(getScore.getSubscribeAmount());// 认购金额

					count_huikuan_price.setText(EmmApplication.isNull(getScore.getReturnAmount()) == false ? "0"
							: getScore.getReturnAmount());// 回款金额

				} else {
					EmmApplication.T(getScore.getErrorMsg().toString());
					Log.v("获取失败", "errorCode:" + getScore.getErrorCode().toString() + "errorMsg:"
							+ getScore.getErrorMsg().toString());
				}
			}
		});
	}

}